import os
import time
import urllib3
import json
import shutil
import requests
import notify
import cdn_refresh

assets_config = {
    "CF_AndroidVersion", "CF_iOSVersion", 
    "CF_AndroidCardsConfig", "CF_iOSCardsConfig",
    "CF_AndroidThemesAssets", "CF_iOSThemesAssets",
    "CF_AndroidActivityConfig", "CF_iOSActivityConfig"
}

chest_config = "SkinChestsIdMap"

def refresh_release_configs(checklist, url_config, request_configs, context):
    cwd = os.getcwd()

    release = url_config["RELEASE"]
    http = urllib3.PoolManager()
    url = release["root_url"]

    awscdn = url_config["AWSCDN"]
    aliyuncdn = url_config["AliyunCDN"]

    history = []
    if os.path.exists(os.path.join(cwd, "refresh_history.json")):
        with open(os.path.join(cwd, "refresh_history.json"), "r") as f:
            history = json.load(f)
    print("history count: " + str(len(history)))

    refreshUrls = []
    configs = []
    r = http.request('GET', url)
    if r.status == 200:
        resp = r.data.decode('unicode_escape')
        # print(resp)

        chestUrl = ""
        data = json.loads(resp)
        for (key, value) in data.items():
            if key in checklist or key in assets_config:
                # print("key " + str(value))
                assetUrl = release["download_url"] + value

                aliyunUrl = assetUrl.replace(awscdn, aliyuncdn)
                if not (aliyunUrl in configs):
                    configs.append(aliyunUrl)

                    if not (aliyunUrl in history):
                        refreshUrls.append(aliyunUrl)

            if key == chest_config:
                chestUrl = release["download_url"] + value
                # print("chest url: " + chestUrl)

        chestReq = http.request('GET', chestUrl)
        if chestReq.status == 200:
            chestResp = chestReq.data.decode('unicode_escape')
            data = json.loads(chestResp)
            for (key, value) in data.items():
                assetUrl = release["download_url"] + value
                aliyunUrl = assetUrl.replace(awscdn, aliyuncdn)
                if not (aliyunUrl in configs):
                    configs.append(aliyunUrl)
                    
                    if not (aliyunUrl in history):
                        refreshUrls.append(aliyunUrl)

        print("refreshUrls:\n" + "\n".join(refreshUrls))
        cdn_refresh.push(refreshUrls)

        # history
        with open(os.path.join(cwd, "refresh_history.json"), "w") as f:
            f.writelines(json.dumps(configs))

        context["Status"] = "Success"
        notify.push_result(context)


